package com.woniuxy.controller;

import com.woniuxy.bean.DataGridView;
import com.woniuxy.bean.ResultDto;
import com.woniuxy.bean.RoleVo;
import com.woniuxy.bean.UserVo;
import com.woniuxy.pojo.Dept;
import com.woniuxy.pojo.User;
import com.woniuxy.service.DeptService;
import com.woniuxy.service.RoleService;
import com.woniuxy.service.UserService;
import org.apache.log4j.Logger;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import javax.xml.transform.Result;
import java.io.File;
import java.io.IOException;
import java.util.List;


@Controller
/*
这里自定义的Controller必须要继承BaseController，如果不继承就会出现时间类型转换的异常
 */
public class UserController extends BaseController{
    private Logger logger= Logger.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;
    @ResponseBody
    @RequestMapping(value = "/users")
    public DataGridView<User> list(UserVo userVo,Integer did){
        System.out.println("did:==="+did);
        /*
        如下三行代码主要是为了迎合layui而做的
         */
        Dept dept=new Dept();
        dept.setId(did);
        userVo.setDept(dept);
        return this.userService.findUsersByPage(userVo);
    }
    @ResponseBody
    @RequestMapping(value = "/selectAllDepts")
    public List<Dept> selectAllDepts(){
        return this.deptService.findAllDepts();
    }
    @RequestMapping(value = "/prepAddUser")
    public String prepAddUser(){
        System.out.println("**************************");
        return "sys/userAdd";
    }
    @ResponseBody
    @RequestMapping(value = "/addUser")
    public ResultDto<User> addUser(User user,
                             @RequestParam("file") MultipartFile file,
                             HttpServletRequest request){
        ResultDto<User> resultDto=new ResultDto<>();
        //获取服务器上路径
        String serverImageDirPath=request.getServletContext().getRealPath("/static/images");
        logger.debug("服务器上的图片文件夹的路径:"+serverImageDirPath);
        String imagePath=serverImageDirPath+"/"+file.getOriginalFilename();
        user.setHeadimg(file.getOriginalFilename());
        File uploadImage=new File(imagePath);
        String password=user.getPassword();
        Object newPassword=new SimpleHash("MD5",password,null,1024);
        user.setPassword(newPassword.toString());
        try {
            file.transferTo(uploadImage);
            this.userService.addUser(user);

            resultDto.setCode(1002);
            resultDto.setMsg("图像上传成功");
            resultDto.setData(user);
        } catch (Exception e) {
            resultDto.setCode(-1002);
            resultDto.setMsg("图像上传失败");
        }
        return resultDto;
    }
    @ResponseBody
    @DeleteMapping(value = "/users/{id}")
    public ResultDto<User> deleteUser(@PathVariable("id") int id){
        ResultDto resultDto=new ResultDto();
        try {
            this.userService.deleteUserById(id);
            resultDto.setCode(1003);
            resultDto.setMsg("删除用户成功");
        } catch (Exception e) {
            resultDto.setCode(-1003);
            resultDto.setMsg("删除用户失败");
        }
        return resultDto;
    }
    @ResponseBody
    @RequestMapping(value = "/users/deleteBatch")
    public ResultDto<User> deleteBatchUser(String ids){
        logger.info(ids+"************");
        ResultDto resultDto=new ResultDto();
        try {
            this.userService.deleteBatch(ids);
            resultDto.setCode(1003);
            resultDto.setMsg("删除用户成功");
        } catch (Exception e) {
            resultDto.setCode(-1003);
            resultDto.setMsg("删除用户失败");
        }
        return resultDto;
    }
    @GetMapping(value = "/prepEditUser")
    public String prepEditUser(){
        return "sys/userEdit";
    }
    @ResponseBody
    @GetMapping(value = "/users/{id}")
    public ResultDto<User> selectUser(@PathVariable("id") Integer id){
        ResultDto<User> resultDto=new ResultDto<>();
        User user=this.userService.findUserById(id);
        resultDto.setData(user);
        return resultDto;
    }
    @ResponseBody
    @GetMapping(value = "/selectRolesByUserId/{id}")
    public DataGridView<RoleVo> selectRolesByUserId(@PathVariable("id") Integer id){
        return this.roleService.findRolesByUid(id);
    }
    @RequestMapping(value = "/prepAssignRole")
    //进入到用户的分配页面
    public String prepAssignRole(){
        return "sys/assignRole";
    }
    @ResponseBody
    @RequestMapping(value = "/assignRole")
    public ResultDto assignRole(@RequestParam("uid") Integer uid,@RequestParam("rids[]")Integer[] rids){
        ResultDto resultDto=new ResultDto();
        try {
            this.userService.assignRole(uid, rids);
            resultDto.setCode(1004);
            resultDto.setMsg("分配角色成功");
        }catch (Exception e){
            resultDto.setCode(-1004);
            resultDto.setMsg("分配角色失败");
        }
        return resultDto;
    }
    @ResponseBody
    @RequestMapping(value = "/updateUser")
    public ResultDto<User> updateUser(User user,
                                   @RequestParam("file") MultipartFile file,
                                   HttpServletRequest request){
        ResultDto<User> resultDto=new ResultDto<>();
        long size=file.getSize();
        logger.info(size+"************");
        /*
        //获取服务器上路径
        String serverImageDirPath=request.getServletContext().getRealPath("/static/images");
        logger.debug("服务器上的图片文件夹的路径:"+serverImageDirPath);
        String imagePath=serverImageDirPath+"/"+file.getOriginalFilename();
        user.setHeadimg(file.getOriginalFilename());
        File uploadImage=new File(imagePath);
        try {
            file.transferTo(uploadImage);
            this.userService.addUser(user);

            resultDto.setCode(1002);
            resultDto.setMsg("图像上传成功");
            resultDto.setData(user);
        } catch (Exception e) {
            resultDto.setCode(-1002);
            resultDto.setMsg("图像上传失败");
        }

        return resultDto;
        */
        return null;
    }


}
